/**
 * Created by henian.xu on 2019/3/8.
 *
 */

import Vue from 'vue';
import Moment from 'dayjs';

import {
  isUrl,
  isString,
  isObject,
  filterNumber,
  GlobalVar,
  changeOldRouteUrl,
} from 'utils';

Vue.filter('moment', (value, format = 'YYYY-MM-DD') => {
  // YYYY-MM-DD HH:mm:ss
  if (!value) return '';
  if (+value) {
    value = +value;
  }
  /* let res = '';
    const now = Moment().startOf('day');
    const moment = Moment(value);
    const diff = now.diff(moment.clone().startOf('day'), 'days');
    if (diff > 0 && diff < 3) {
        // format = format.replace('YYYY-MM-DD', '');
        format = format.replace(/YYYY(.*)MM(.*)DD/, '').trim();
        res = format ? moment.format(format) : '';
        if (diff === 1) {
            res = `昨天${res}`;
        } else if (diff === 2) {
            res = `前天${res}`;
        }
    } else {
        res = moment.format(format);
    } */
  return Moment(value).format(format);
});

Vue.filter('substringStr', (value) => {
  const maxLength = 20;
  if (value.length > maxLength) {
    return `${value.substring(0, maxLength)}...`;
  }
  return value;
});

Vue.filter('number', (value, length = 2, strict = true) =>
  filterNumber(value, length, strict),
);

Vue.filter('price', (value, length = 0, strict = false) => {
  const amountFormat = `${GlobalVar.moduleConfig.amountFormat}`;
  const signStrict = amountFormat.charAt(0) !== '+';
  const arr = amountFormat.split('.');
  const len = arr.length < 2 ? 0 : arr[1].length;
  return filterNumber(value, length || len, strict || signStrict);
});

Vue.filter('htmlDecode', (value) => {
  if (value === '' || value === undefined || value === null) return '';
  const node = document.createElement('div');
  node.innerHTML = value;
  return node.innerText || '';
});

Vue.filter('money', (value = '') => {
  value += '';
  return value.replace(/\B(?=(\d{3})+(?!\d))/g, ',') || 0;
});

Vue.filter('imgCropping', (value, { width = 750 } = {}) => {
  value += '';
  const { moduleConfig } = GlobalVar;
  if (
    !value ||
    !moduleConfig ||
    !moduleConfig.imgCropping ||
    value.indexOf(GlobalVar.ossFilePath) !== 0
  ) {
    return value;
  }
  // const extensionName = value.replace(/.+\./, '');
  return `${value}${width ? `@${width}w` : ''}`;
});

/**
 * imgCropping
 * mini: 100
 * small: 200
 * little: 375
 * normal: 750
 * big: 900
 * more: 1200
 * super: 1920
 */
Vue.filter('imgCropping', (value, params = 'normal') => {
  value += '';
  // const { moduleConfig: { imgCropping } = {} } = GlobalVar;
  // if (!value || !imgCropping) return value;
  // const imgCroppingList = isArray(imgCropping) ? imgCropping : [imgCropping];
  // const available = imgCroppingList.some(val => isString(val) && value.indexOf(val) === 0);
  // console.log(available, params);
  // if (!available) return value;
  if (!value || !isUrl(value)) return value;
  if (params && isString(params)) {
    const styleNameMap = {
      mini: { width: 100 },
      small: { width: 200 },
      little: { width: 375 },
      normal: { width: 750 },
    };
    params = styleNameMap[params] || '';
  }
  if (params && isObject(params)) {
    // doc: https://help.aliyun.com/document_detail/44688.html?spm=a2c4g.11186623.6.1372.11313168wqiX8s
    const keyMap = {
      mode: 'm', // lfit、mfit、fill、pad、fixed，默认为 lfit。
      width: 'w',
      height: 'h',
      long: 'l',
      short: 's',
      limit: 'limit',
      color: 'color',
    };
    const query = Object.entries(params)
      .reduce(
        (pre, [key, val]) => {
          const k = keyMap[key];
          if (k) pre.push(`${k}_${val}`);
          return pre;
        },
        ['image/resize'],
      )
      .join(',');
    const fn = '?x-oss-process=';
    return `${value}${fn}${query}`;
  }
  return value;
});

// 暂无引用
Vue.filter('richTextLink', (value) => {
  if (!value) return value;

  // const reg = /href=["|'](.*?)["|']/;
  const res = value.replace(/<a\b.*?<\/a>/gi, (a) => {
    return a.replace(/href=["|'](.*?)["|']/i, (href, g1) => {
      const path = changeOldRouteUrl(g1);
      if (!path) return href;
      return `href="${path}"`;
    });
  });
  // console.log(res);

  return res;
});
